<!--
 * @Author: wei_jt@ecidi.com
 * @Date: 2019-11-09 10:32:49
 * @LastEditors: wei_jt@ecidi.com
 * @LastEditTime: 2022-03-31 10:40:51
 * @Description: 应用配置
 -->
<template>
  <div class="body">
    <div class="overview">
      {{ LANG.OVERVIEW }}
    </div>
    <div style="margin-bottom: 24px; font-size: 16px; color: #191919">
      使用契约锁签章前请先上传签章文件填写合同标题、发起人、联系方式，选择签章类型以及签约方。
    </div>
    <div style="display: flex">
      <div class="titleStyle">
        选择签章流程
      </div>
      <fks-select
        v-model="categoryName"
        class="signInput"
        clearable
        @change="changeFlowData"
      >
        <fks-option
          v-for="item in flowData"
          :key="item.code"
          :value="item.code"
          :label="item.label"
        />
      </fks-select>
    </div>
    <div class="overview">
      {{ LANG.UPLOAD_FILE }}
    </div>
    <div style="width: 50%">
      <fks-upload
        :action="uploadUrl"
        drag
        name="file"
        :headers="{
          'Fawkes-Auth': ACESS_TOKEN
        }"
        class="pdfSign"
        :with-credentials="true"
        :auto-upload="true"
        :limit="1"
        accept=".pdf"
        :file-list="fileList"
        :http-request="uploadPdf"
      >
        <i class="fks-icon-upload" />
        <div class="fks-upload__text">
          <span>{{ LANG.DRAG_CLICK }}</span>
          <br>
          <span>{{ LANG.SUPPORT_PDF }}</span>
        </div>
      </fks-upload>
    </div>
    <div style="display: flex; margin-top: 24px">
      <div class="titleStyle">
        合同标题
      </div>
      <fks-input
        v-model="subject"
        class="signInput"
      />
    </div>
    <div style="display: flex; margin-top: 24px">
      <div class="titleStyle">
        发起人
      </div>
      <fks-input
        v-model="creatorName"
        class="signInput"
      />
    </div>
    <div style="display: flex; margin-top: 24px">
      <div class="titleStyle">
        联系方式
      </div>
      <fks-input
        v-model="creatorContact"
        class="signInput"
      />
    </div>
    <div style="display: flex; margin-top: 24px">
      <div class="titleStyle">
        签章类型
      </div>
      <fks-select
        v-model="signType"
        class="signInput"
        clearable
        @change="changeSignType"
      >
        <fks-option
          v-for="item in signTypeList"
          :key="item.value"
          :value="item.value"
          :label="item.label"
        />
      </fks-select>
    </div>
    <div style="display: flex; margin-top: 24px">
      <div class="titleStyle">
        签约方
      </div>
      <fks-select
        v-model="signPeople"
        class="signInput"
        :multiple="this.signType != 'COMPANY'"
        clearable
        @change="changeSignPeople"
      >
        <fks-option
          v-for="item in signPeopleList"
          :key="item.value"
          :value="`${item.label}|${item.value}`"
          :label="item.label"
        />
      </fks-select>
    </div>
    <fks-button
      v-if="this.signType == 'PERSONAL'"
      style="margin: 24px 24px 0 0px"
      @click="signPdf"
    >
      个人签章
    </fks-button>
    <fks-button
      v-if="this.signType == 'COMPANY'"
      style="margin: 24px 0 0 0px"
      @click="companySignPdf"
    >
      公章
    </fks-button>
    <fks-button
      v-if="this.signType == 'PERSONAL'"
      style="margin: 24px 0 0 0px"
      @click="signIframe"
    >
      个人签章（iframe）
    </fks-button>
    <fks-button
      style="margin: 24px 0 0 24px"
      @click="preview"
    >
      {{ LANG.PREVIEW }}
    </fks-button>
    <Signature ref="Signature" />
    <fks-dialog
      :visible="previewPdf"
      :append-to-body="true"
      @close="closePreview"
    >
      <div slot="title">
        {{ LANG.PREVIEW }}
      </div>
      <pre-view
        v-if="previewPdf"
        :file-token="fileToken"
        style="height: 800px"
      />
    </fks-dialog>
  </div>
</template>

<script>
import pdfSign from '@/components/PdfSignature/index.vue'
import Signature from '@/components/PdfSignature/contractLock.vue'
import PreView from '@/components/PreView/index'
import { sign, upload, preview, getFlow, getUserName } from './api'
export default {
  name: 'ContractLock',
  components: { pdfSign, PreView, Signature },
  data() {
    return {
      uploadVisible: false,
      english: false,
      uploadUrl: '',
      ACESS_TOKEN: this.$storage.get('access_token'),
      fileList: [],
      licFileList: [],
      fileToken: '',
      keySn: 'chen_m2',
      sign: false,
      previewPdf: false,
      expiration: '',
      signParams: new FormData(),
      file: {},
      signData: [],
      flowData: [],
      url: '',
      categoryId: '',
      categoryName: '',
      deleteFlag: false,
      signType: 'PERSONAL',
      signPeople: '田野|18388466441',
      userName: '',
      userFullName: '',
      signTypeList: [
        { label: '个人签章', value: 'PERSONAL' },
        { label: '公章', value: 'COMPANY' }
      ],
      signPeopleList: [
        { label: '高飞明', value: '18262633796' },
        { label: '田野', value: '18388466441' }
      ],
      signPeopleData: [],
      licInfo: '',
      fileData: '',
      creatorName: '陈冲测试',
      creatorContact: '15617901095',
      subject: ''
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getFlowData()
  },
  methods: {
    changeSignPeople(value) {
      this.signPeople = value
      this.signPeopleData = []
      if (this.signType == 'COMPANY') {
        this.signPeopleData.push(value.split('|'))
      } else {
        this.signPeopleData = []
        value.forEach((item) => {
          this.signPeopleData.push(item.split('|'))
        })
      }
    },
    changeSignType(value) {
      this.signType = value
    },
    signIframe() {
      if (this.url) {
        this.$refs.Signature.signIframe(this.url)
      } else {
        this.$message.error('请先进行个人签章')
      }
    },
    getFlowData() {
      getFlow({ name: '中国电建集团华东勘测设计研究院有限公司' }).then(
        (res) => {
          if (res.status) {
            for (let item in res.data) {
              this.flowData.push({ code: item })
            }
          }
          this.flowData.forEach((item) => {
            item.label = res.data[item.code]
          })
          this.categoryId = this.flowData[0].code
          this.categoryName = this.flowData[0].label
        }
      )
    },
    changeFlowData(value) {
      this.categoryId = value
    },
    //个人签名
    signPdf() {
      if (this.signParams.get('fileName') && this.signParams.get('file')) {
        this.$message.success('正在上传签章文件')
        upload(this.signParams)
          .then(async (res) => {
            if (this.creatorName && this.creatorContact && this.subject) {
              let phoneList = []
              let userData = {}
              this.signPeopleData.forEach((item) => {
                phoneList.push(item[1])
              })
              await getUserName({ phones: phoneList.toString() }).then(
                (res) => {
                  if (res.status) {
                    userData = res.data
                  }
                }
              )
              let params = {
                subject: this.subject, //,主题：合同标题
                documents: [res.data], //上传文档对应ID
                tenantName: '中国电建集团华东勘测设计研究院有限公司', //签章归属组织
                categoryId: this.categoryId, //用章流程ID
                creatorName: this.creatorName, //发起人-契约锁平台账号发起人名字
                creatorContact: this.creatorContact, //发起人联系方式对应账号下的联系方式
                signatories: [], //签署人列表
                fromUserName: this.$storage.get('username'),
                toUserMap: {}
              }
              this.signPeopleData.forEach((item) => {
                params.signatories.push({
                  tenantType: 'PERSONAL', //签章类型：个人、公章COMPANY
                  tenantName: item[0], //接收人·
                  receiverName: item[0], //接收人
                  contact: item[1], //接收人电话号码
                  remind: true //是否短信提醒
                })
                params.toUserMap[item[0]] = userData[item[0]]
              })
              sign(params)
                .then((res) => {
                  this.signData = res.data
                  let userData = JSON.parse(this.$storage.get('user'))
                  let signDataList = []
                  if (res.data.length > 0) {
                    signDataList = res.data.find((item) => {
                      return item.mobile == userData.phone
                    })
                    if (signDataList) {
                      window.open(signDataList.url)
                      this.url = signDataList.url
                    } else {
                      this.$message.success('合同发送成功')
                    }
                  }
                })
                .catch(() => {})
            } else {
              this.$message.error('请填写合同标题、发起人、联系方式')
            }
          })
          .catch(() => {})
      } else {
        this.$message.error('请先上传待签章文件')
      }
    },
    //公章
    companySignPdf() {
      if (this.signParams.get('fileName') && this.signParams.get('file')) {
        this.$message.success('正在上传签章文件')
        upload(this.signParams)
          .then(async (res) => {
            if (this.creatorName && this.creatorContact && this.subject) {
              let phoneList = []
              let userData = {}
              this.signPeopleData.forEach((item) => {
                phoneList.push(item[1])
              })
              await getUserName({ phones: phoneList.toString() }).then(
                (res) => {
                  if (res.status) {
                    userData = res.data
                  }
                }
              )
              let params = {
                subject: this.subject, //主题：合同标题
                documents: [res.data], //上传文档对应ID
                tenantName: '中国电建集团华东勘测设计研究院有限公司', //发起方组织名称
                categoryId: this.categoryId, //用章流程ID
                fromUserName: this.$storage.get('username'), //需要发送站内信时需要增加参数发送人用户名
                creatorName: this.creatorName, //发起人-契约锁平台账号发起人名字
                creatorContact: this.creatorContact, //发起人联系方式对应账号下的联系方式
                fromUserName: this.$storage.get('username'),
                toUserMap: {},
                //一个公司的公章签署只需要一个用户即可
                signatories: [
                  {
                    //签署人列表
                    tenantType: 'COMPANY', //公章COMPANY
                    tenantName: '中国电建集团华东勘测设计研究院有限公司', //接收方组织名称
                    receiverName: this.signPeopleData[0][0], //接收人姓名
                    contact: this.signPeopleData[0][1], //接收人联系方式
                    remind: true, //是否开启提示-短信
                    actions: [
                      {
                        type: 'CORPORATE',
                        name: '公章',
                        serialNo: 1, //签章动作顺序，不指定时都传1，指定顺序从1开始
                        actionOperators: [
                          {
                            operatorName: this.signPeopleData[0][0], //动作执行人
                            operatorContact: this.signPeopleData[0][1] //动作执行人联系方式
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
              params.toUserMap[this.signPeopleData[0][0]] =
                userData[this.signPeopleData[0][0]]
              sign(params)
                .then((res) => {
                  this.signData = res.data
                  let userData = JSON.parse(this.$storage.get('user'))
                  let signDataList = []
                  if (res.data.length > 0) {
                    signDataList = res.data.find((item) => {
                      return item.mobile == userData.phone
                    })
                    if (signDataList) {
                      window.open(signDataList.url)
                      this.url = signDataList.url
                    } else {
                      this.$message.success('合同发送成功')
                    }
                  }
                })
                .catch(() => {})
            } else {
              this.$message.error('请填写合同标题、发起人、联系方式')
            }
          })
          .catch(() => {})
      } else {
        this.$message.error('请先上传待签章文件')
      }
    },
    //上传文件
    uploadPdf(params) {
      // 根据后台需求数据格式
      this.signParams = new FormData()
      // 文件对象
      this.signParams.append('file', params.file)
      this.signParams.append('fileName', params.file.name)
      this.signParams.append('height', '')
      this.signParams.append('pic', '')
      this.signParams.append('watermarkFont', '')
      this.signParams.append('width', '')
    },
    //预览
    preview() {
      if (this.signParams.get('fileName') && this.signParams.get('file')) {
        let previewData = {}
        let userData = JSON.parse(this.$storage.get('user'))
        if (this.signData.length > 0) {
          previewData = this.signData.find((item) => {
            return item.mobile == userData.phone
          })
          if (previewData) {
            preview({
              contractId: previewData.contractId,
              documentId: previewData.documentId
            })
              .then((result) => {
                window.open(result.data)
              })
              .catch(() => {})
          } else {
            this.$message.error('您非签署人员，无法预览')
          }
        } else {
          this.$message.error('请先签章再预览')
        }
      } else {
        this.$message.error('请先上传待签章文件')
      }
    },
    closePreview() {
      this.previewPdf = false
    }
  }
}
</script>
<style scoped lang="scss">
.body {
  width: 100%;
  height: 100%;
  padding: 24px 50px;
  overflow-y: auto;
  font-size: 14px;
  background-color: white !important;
}

.overview {
  margin-bottom: 24px;
  font-weight: bold;
  font-size: 16px;
  color: #191919;
}

::v-deep .fks-upload {
  width: 424px;
}
::v-deep .fks-upload-dragger {
  width: 424px;
}
.titleStyle {
  margin-right: 24px;
  font-weight: bold;
  font-size: 16px;
  width: 100px;
}
.signInput {
  width: 300px;
}
.english {
  ::v-deep .fks-input__inner {
    margin-left: 15px;
  }
}
</style>
